package com.innovation.chengzhangriji.ui;


import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.LoginResponse;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.animation.AnimationConfig;
import com.innovation.chengzhangriji.ui.widget.CuteButton;
import com.innovation.chengzhangriji.ui.widget.CuteEditGroup;
import com.innovation.chengzhangriji.ui.widget.CuteTimerButton;
import com.jiuan.oa.android.library.util.MobileNumberUtil;
import com.umeng.analytics.MobclickAgent;

public class LoginDynamicFragment extends BaseLoginFragment implements View.OnClickListener, CuteTimerButton.TimerListener {

    private String second;

    private CuteEditGroup mCegNumber;

    private RelativeLayout mLayout;

    private CuteEditGroup mCegCode;

    private CuteTimerButton mCtbTimer;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        second = getString(R.string.button_timer);
        View view = inflater.inflate(R.layout.fragment_login_dynamic, container, false);
        mCegNumber = (CuteEditGroup) view.findViewById(R.id.edit_text_number);
        mLayout = (RelativeLayout) view.findViewById(R.id.layout);
        mCegCode = (CuteEditGroup) view.findViewById(R.id.edit_text_code);
        mCtbTimer = (CuteTimerButton) view.findViewById(R.id.button_timer);
        mCtbTimer.setText("获取验证码");
        mCtbTimer.setTimerListener(this);
        CuteButton button = (CuteButton) view.findViewById(R.id.btn_login);
        button.setOnClickListener(this);
        return view;
    }

    @Override
    protected void onPageStart() {
        MobclickAgent.onPageStart(Config.UMENG_PAGE_LOGIN_DYNAMIC);
    }

    @Override
    protected void onPageEnd() {
        MobclickAgent.onPageEnd(Config.UMENG_PAGE_LOGIN_DYNAMIC);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_login) {
            String number = mCegNumber.getContent();
            String code = mCegCode.getContent();
            if (checkInput(number, code)) {
                InputMethodManager manager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                manager.hideSoftInputFromWindow(mLayout.getWindowToken(), 0);
                requestDynamicLogin(number, code);
            }
        }
    }

    @Override
    public void timerStart(View v, int startCount) {
        if (v.getId() == R.id.button_timer) {
            mCtbTimer.setText(startCount + second);
            String code = mCegNumber.getContent();
            if (checkNumber(code)) {
                mCtbTimer.setTextColor(Color.LTGRAY);
                requestDynamicLoginGetCode(code);
            } else {
                stopTime();
            }
        }
    }

    @Override
    public void timerCount(View v, int currentCount) {
        if (v.getId() == R.id.button_timer) {
            mCtbTimer.setText(currentCount + second);
        }
    }

    @Override
    public void timerEnd(View v) {
        if (v.getId() == R.id.button_timer) {
            mCtbTimer.setTextColor(Color.BLACK);
            mCtbTimer.setText("再次获取");
        }
    }

    private boolean checkNumber(String number) {
        if (!MobileNumberUtil.isMobile(number)) {
            AnimationConfig.shake(getActivity(), mCegNumber);
            tipShow(R.string.tip_error_number);
            return false;
        }
        return true;
    }

    private boolean checkInput(String number, String code) {
        if (!checkNumber(number)) {
            return false;
        }
        if (TextUtils.isEmpty(code)) {
            AnimationConfig.shake(getActivity(), mLayout);
            tipShow(R.string.tip_error_code_empty);
            return false;
        }
        return true;
    }

    public void stopTime() {
        mCtbTimer.stop();
    }

    private void requestDynamicLogin(final String number, final String code) {
        Client.requestDynamicLogin(getActivity(), number, code, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                dismissProgressDialog();
                if (mLoginSuccessListener != null) {
                    LoginResponse response = get(value.toString(), LoginResponse.class);
                    if (response!=null){
                        LoginInfo login = new LoginInfo();
                        login.setUserID(response.getId());
                        login.setName(response.getUserName());
                        login.setPhone(number);
                        login.setGender(response.getGender());
                        login.setUrl(response.getUrl());
                        login.setToken(response.getToken());
                        mLoginSuccessListener.loginSuccess(login);
                    }
                }
            }

            @Override
            public void onChZhRJFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }

        }, networkUnavailableSampleImpl());
    }

    private void requestDynamicLoginGetCode(final String phone) {
        // 当未连接网络,或网络连接超时的情况发生时,重置计时器.
        Client.requestDynamicLoginGetCode(getActivity(), phone, new ResponseHandler() {

            @Override
            public void onInnovationExceptionFinish() {
                super.onInnovationExceptionFinish();
                stopTime();
            }

        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {
                tipShow(R.string.tip_network_unavailable);
                stopTime();
            }
        });
    }
}
